import axios from 'axios'
import { httpConfig, getToken, removeToken } from '@/config'
import { Loading, Message } from 'element-ui'
import store from '@/store/back'
const qs = require('qs');
console.log(httpConfig().baseUrl)
axios.defaults.timeout = 30000
let loadingInstance
// 接口拦截配置 
const NOT_LOADING = 1
const NOT_INTERCETOR = 2
const fecth = axios.create({
    baseUrl: httpConfig().baseUrl,
    ourConfig: 0
})

const requestUse = (config) => {
    const ourConfig = config.ourConfig
    config.headers = {
        // token: getToken()
        // 'access_token': getToken(),
        // 'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: localStorage.getItem('token_type') ? `${localStorage.getItem('token_type')} ${getToken()}` : 'basic bWljcm86MTIzNDU2'
    }
    if (!(ourConfig & NOT_LOADING)) {
        loadingInstance = Loading.service({ background: 'rgba(0,0,0,.1)', fullscreen: true })
    }
    return config
}

const responseSuccess = (response) => {
    const ourConfig = response.config.ourConfig
    // const code = response.data.code
    const res = response.data
    const code = response.data.code
    if (!(ourConfig & NOT_LOADING)) {
        loadingInstance.close()
    }
    
    if (ourConfig & NOT_INTERCETOR) {
        return res
    }
    if (!code) {
        return res
    }
    console.log(code)
    if (code === 200) {
        return res.data
    }
    if (code === 401) { // token失效退出登录
        console.log(store)
        store.dispatch('user/FedLogOut')
    }
    if (code !== 200) {
        Message.warning(res.msg)
        return Promise.error(res.msg)
    }
    return res
}

const responseError = (error) => {
    if (loadingInstance) {
        loadingInstance.close()
    }
    if (error.response.status === 403 && error.response.data.code && error.response.data.code===401) {
        store.dispatch('FedLogOut')
    }
    if (error.response.data && error.response.data.msg) {
        Message.error(error.response.data.msg)
    }
    return Promise.reject(error)
}

fecth.interceptors.request.use(requestUse)
fecth.interceptors.response.use(responseSuccess, responseError)


export const axiosAjax = (method, url, params, config) =>{
    let data
    let base_url
    if (method === 'post') {
      data = 'data'
    } else {
      data = 'params'
    }
    console.log(qs)
    console.log(httpConfig().baseUrl)
    return fecth({
      method: method,
      url: httpConfig().baseUrl + url,
    //   url: '/api'+url,
      [data]: params,
    //   [data]: data === 'data' ? qs.stringify(params) ? qs.stringify(params) : params : params,
      ourConfig: config
    })
  }

  export const pageDataExport = (method, exportUrl, params, filename, failCallback) => {
    let loadingInstance = Loading.service({ background: 'rgba(0,0,0,.1)', fullscreen: true })
    axios({
      url: httpConfig().baseUrl + exportUrl,
      responseType: 'blob',
      method: method,
      data: params || {},
      headers: {
        Authorization: localStorage.getItem('token_type') ? `${localStorage.getItem('token_type')} ${getToken()}` : 'basic bWljcm86MTIzNDU2'
      }
    }).then(res => {
      if (loadingInstance) {
        loadingInstance.close()
      }
      if (res.data) {
        let blob = res.data;
        let reader = new FileReader();
        reader.readAsDataURL(blob); // 转换为base64，可以直接放入a标签href
        reader.onload = function (e) {
          let a = document.createElement('a');
          a.className = 'excel_box';
          a.download = filename;
          a.href = e.target.result;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(e.target.result);
        }
      } else {
        let err = {
          code: 1,
          msg: "导出文件失败"
        };
        failCallback && failCallback(err);
      }
    }).catch(function (error) {
      if (loadingInstance) {
        loadingInstance.close()
      }
      let err = {
        code: -1,
        msg: "服务器异常"
      };
      failCallback && failCallback(err);
    });
  }